<template>
  <div class="app-navbar">
    <div class="navbar-left">
      <h2>Alpha智考系统</h2>
    </div>
    <div class="navbar-right">
      <span class="welcome-text">欢迎, {{ username }} ({{ roleText }})</span>
      <el-button type="danger" size="small" @click="logout">退出登录</el-button>
    </div>
  </div>
</template>

<script>
import axios from '@/utils/request'

export default {
  name: 'AppNavbar',
  props: {
    title: {
      type: String,
      default: ''
    },
    role: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      username: '',
      roleId: null
    }
  },
  computed: {
    roleText() {
      switch (this.roleId) {
        case 1: return '管理员';
        case 2: return '教师';
        case 3: return '学生';
        default: return '用户';
      }
    }
  },
  created() {
    // 从localStorage获取用户信息
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      try {
        const user = JSON.parse(userInfo);
        this.username = user.username;
        this.roleId = user.roleId;
      } catch (e) {
        console.error('解析用户信息失败:', e);
      }
    }
  },
  methods: {
    async logout() {
      try {
        // 调用后端退出登录接口
        await axios.post('/auth/logout');
      } catch (error) {
        console.error('退出登录请求失败:', error);
      } finally {
        // 清除本地存储的用户信息
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        
        // 跳转到登录页面
        this.$router.push('/login');
      }
    }
  }
}
</script>

<style scoped>
.app-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #409eff;
  color: white;
  border-radius: 5px;
  margin-bottom: 20px;
}

.navbar-left h2 {
  margin: 0;
  color: white;
}

.navbar-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.welcome-text {
  font-size: 14px;
}
</style>